import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types'; // ES6

import './search.scoped.less';

function Search(props) {
  const [searchValue, setSearchValue] = useState(props.value || ''); // 搜索框的值
  const [searchList, setSearchList] = useState(props.searchList); // 搜索结果
  const [searchListCopy, setSearchListCopy] = useState(props.searchList); // 搜索备用
  const [listItem, setListItem] = useState({}); // 当前选中的列表item
  const timer = useRef();

  const field = props.field || 'value';
  const fieldKey = props.fieldKey || 'index';

  // 搜索内容改变触发
  const searchChange = (e) => {
    const { value } = e.target;
    setSearchValue(value);
    if (typeof props.valueChange === 'function') {
      clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        props.valueChange(value);
      }, 300);
    }
  };
  // 点击取消
  const cancel = () => {
    // history.go(-1);
    props.cancel && props.cancel();
  };
  // 点击选中某一项
  const selectListItem = (item) => {
    setSearchList([]);
    setListItem(item);
    setSearchValue(item[field]);
    if (typeof props.selectChange === 'function') {
      props.selectChange(item);
    }
  };
  // 输入框聚焦
  const onFocus = (e) => {
    if (typeof props.onFocus === 'function') {
      props.onFocus(e);
    }
  };
  // 清空输入框的值
  const clearSearchValue = () => {
    setSearchValue('');
  };

  useEffect(() => {
    setSearchList(props.searchList);
    setSearchListCopy(props.searchList);
    // console.log('listItem');
  }, [props.searchList]);

  useEffect(() => {
    if (!fieldKey && props.showList) {
      console.error('组件必须接收一个[fieldKey]字段来作为搜索列表的唯一key');
    }
    //
    return () => {
      clearTimeout(timer.current);
    };
  }, []);
  // console.log(listItem[fieldKey]);

  return (
    <div className={`Search fx fx-ai-c ${props.className}`}>
      <div className="input input-box fx1 fx fx-ai-c">
        <input
          value={searchValue}
          onChange={searchChange}
          type="text"
          className="input fx1 no-border"
          placeholder={props.placeholder || ''}
        />
        {searchValue.length > 0 && (
          <span className="clear" onClick={clearSearchValue}>
            X
          </span>
        )}
      </div>
      {props.onCancel && (
        <span className="text fx0" onClick={cancel} onFocus={onFocus}>
          {props.cancelContent || '取消'}
        </span>
      )}

      {/* 搜索结果 */}
      <div className={`search-list ${searchList.length > 0 && props.showList ? 'show' : ''}`}>
        {searchList.map((item, index) => {
          return (
            <div
              className={`li ${listItem[fieldKey] === item[fieldKey] ? 'select' : ''}`}
              key={item[fieldKey] || index}
              onClick={() => selectListItem(item)}
            >
              {props.renderList ? props.renderList : item[field]}
            </div>
          );
        })}
      </div>
      {/*  */}
    </div>
  );
}

Search.propTypes = {
  value: PropTypes.string, // 搜索框默认值
  cancel: PropTypes.func, // 点击取消
  showList: PropTypes.bool, // 是否要显示搜索下拉列表
  onFocus: PropTypes.func, //聚焦时调用
  placeholder: PropTypes.string, // 输入框默认提示
  onCancel: PropTypes.func,
};

export default Search;
